const _ = require('lodash');
const moment = require('moment');
const ms = require('ms');

const prefix = '/api/project';

/**
 * 检查用户与项目的关系
 * @param ctx
 * @param next
 * @returns {Promise<void>}
 */
const checkLevel3 = async (ctx, next) => {
  const {id} = ctx.params;
  const project = await ctx.app.model.Project.findByPk(id);
  if (!project)
    return ctx.helper.error('不存在的项目');
  ctx.project = project;
  ctx.role = await ctx.service.project.userRole(id, ctx.user.id);

  if (ctx.role === -1)
    return ctx.helper.error('没有操作这个项目的权限');
  await next();

};

module.exports = app => {
  const {router, middleware, model, spider} = app;

  /**显示项目列表*/
  router.get(prefix, middleware.api(), async ctx => {
    const {User, Project} = ctx.app.model;
    const {page, limit, offset} = ctx.service.page.page();
    const where = {};
    const order = [['created_at', 'desc']];

    if (!_.isEmpty(ctx.query.search))
      where.name = {[ctx.app.Sequelize.Op.like]: '%' + ctx.query.search + '%'};

    let total, list;
    if (ctx.user.level.id <= 2) {//管理员，列出所有项目
      total = await Project.count({where});
      list = await Project.findAll({
        limit, offset,
        order,
        where,
      });
    } else {//只列出与自己相关的项目
      const user = User.build({id: ctx.user.id}, {isNewRecord: false});
      total = await user.countProject({where});
      list = await user.getProject({limit, offset, order, where});
    }
    ctx.body = {page, total, list};

  });

  /**新建 或  编辑  项目*/
  router.post(prefix, middleware.api(2), async ctx => {
    const data = ctx.request.body;
    const {id, name, categories, time, options} = data;
    if (_.isEmpty(name))
      return ctx.helper.error('请填写项目名称');
    if (_.isEmpty(options.aggregation))
      return ctx.helper.error('必须添加 直播分类');
    if (_.isEmpty(time) || _.isEmpty(time[0]) || _.isEmpty(time[1]))
      return ctx.helper.error('必须添加 运营时间');

    const start_at = time[0], end_at = time[1],
        email = !!data.email ? data.email.trim() : '';
    let project;
    if (id > 0) {//编辑
      project = await app.model.Project.findByPk(id);
      if (!project)
        return ctx.helper.error('不存在的项目');
      await project.update(
          {name, start_at, end_at, email, options: data.options});
      // await project.setPlatformCategory(categories);
      ctx.service.event.add({
        content: '编辑项目',
        project: _.pick(project, ['id', 'name']),
      });
    } else {//新建
      if (0 !== await ctx.app.model.Project.count({where: {name}}))
        return ctx.helper.error('项目名称已被使用');
      project = await ctx.app.model.Project.create(
          {name, start_at, end_at, email, options: data.options});
      // await project.addPlatformCategory(categories);
      ctx.app.model.Report.create({
        project_id: project.id,
        created_at: Date.now() - ms('1 day'),
      });
      ctx.service.event.add({
        content: '创建项目',
        project: _.pick(project, ['id', 'name']),
      });
    }
    ctx.body = project;
  });

  /**显示项目内容*/
  router.get(prefix + '/:id', middleware.api(), checkLevel3, async ctx => {
    const {id: project_id} = ctx.params;
    const {DailyPlatformCategory, Platform, DailyCategory, Project, User} = model;

    let project = await Project.findOne({
      where: {id: project_id},
      include: [{model: User, as: 'user', required: false}],
    });

    if (!project)
      return ctx.helper.error('不存在的项目');
    project = project.toJSON();
    project.platformTypes = [];
    let pcId = [];
    if (!_.isEmpty(project.options.aggregation)) {
      project.options.aggregation.forEach(item => {
        pcId = pcId.concat(item.data);
      });
    }
    if (pcId.length > 0) {
      project.platformTypes = await spider.PlatformType.findAll(
          {
            where: {id: {[ctx.app.Sequelize.Op.in]: pcId}},
            include: [{model: spider.Platform}, {model: spider.Type}],
          });
    }
    project.role = ctx.role;
    ctx.body = project;
  });

  /**获取 项目 所有 邮箱地址*/
  router.get(prefix + '/:id/email', middleware.api(4), checkLevel3,
      async ctx => {
        const emails = _.compact(ctx.project.email.split('\n'));
        const users = await ctx.project.getUser(
            {attributes: ['username', 'email']});
        emails.forEach((mail, i) => {
          emails[i] = {email: mail, role: '项目内置'};
        });
        users.forEach(user => {
          let role = '项目执行';
          if (user.user_project.type === 0)
            role = '项目管理';
          else if (user.user_project.type === 1)
            role = '项目执行';
          emails.push({email: user.email, username: user.username, role});
        });
        ctx.body = emails;
      });

  /**按月份读取项目日报的日期，用于项目页面的日历点击看日报功能*/
  router.get(prefix + '/:id/calendar/:date', middleware.api(), checkLevel3,
      async ctx => {
        let {id: project_id, date} = ctx.params;
        const {between} = ctx.app.Sequelize.Op;
        const monthStart = moment(date).startOf('month').toDate(),
            monthEnd = moment(date).endOf('month').toDate();
        const list = await ctx.app.model.Report.findAll({
          where: {project_id, created_at: {[between]: [monthStart, monthEnd]}},
          attributes: ['created_at'],
          order: [['created_at', 'asc']],
          group: ['created_at'],
        });
        ctx.body = list.map(item => item.created_at);
      });

  /**删除项目*/
  router.del(prefix, middleware.api(2), async ctx => {
    let id = ctx.query.id;
    if (_.isEmpty(id))
      return ctx.helper.error('缺少ID');
    id = _.compact(id.split(','));
    if (_.isEmpty(id))
      return ctx.helper.error('缺少ID');
    await app.model.Project.update({delete: true},
        {where: {id: {[app.Sequelize.Op.in]: id}}});
    ctx.body = 'ok';
  });

  /**参与过项目的主播 历史*/
  router.get(prefix + '/:id/anchors/history', middleware.api(), checkLevel3,
      async ctx => {
        const {id: project_id} = ctx.params;
        const schedules = await app.model.ProjectAnchor.findAll({
          where: {project_id},
          include: [
            {
              model: ctx.app.model.DetailAnchor,
              as: 'anchor',
              include: [{model: app.model.Platform}],
            }],
        });
        ctx.body = _.groupBy(schedules, 'anchor.platform.name');
      });

  /**添加 或 编辑 时间记录*/
  router.post(prefix + '/:id/anchor/schedule', middleware.api(4), checkLevel3,
      async ctx => {
        const {DetailAnchor, Platform, DetailAnchorSchedule, ProjectAnchor} = ctx.app.model;
        const {id: project_id} = ctx.params;
        let {id: schedule_id, start, end, loop, anchor} = ctx.request.body;

        start = new Date(start);
        end = new Date(end);
        if (start >= end)
          return ctx.helper.error('开始时间不能大于等于结束时间');

        if (0 === await ProjectAnchor.count(
            {where: {project_id, anchor_id: anchor.id}}))
          await ProjectAnchor.create({project_id, anchor_id: anchor.id});

        console.log('count', await ProjectAnchor.count(
            {where: {project_id, anchor_id: anchor.id}}));
        return ctx.body = 'ok';

        //存在schedule_id，修改
        if (schedule_id > 0) {
          const schedule = await DetailAnchorSchedule.findByPk(schedule_id);
          if (!schedule)
            return ctx.helper.error('正在编辑不存在的记录');
          const data = {start, end};
          if (loop && loop > 0)
            data.loop = loop;
          await schedule.update(data);
          ctx.body = schedule;
        }
        else {//创建
          if (!(loop >= 1))
            return ctx.helper.error('截图间隔时间不能少于1');
          const newSchedule = await DetailAnchorSchedule.create({
            anchor_id: anchor.id, platform_id: anchor.platform_id, project_id,
            start: start, end: end, loop: loop,
          });

          ctx.body = await DetailAnchorSchedule.findOne({
            where: {id: newSchedule.id},
            include: [{model: DetailAnchor, as: 'anchor'}, {model: Platform}],
          });
        }
      });

  /**删除项目中主播的直播时间记录*/
  router.del(prefix + '/:id/anchor/:anchor_id/schedule/:schedule_id',
      middleware.api(4), checkLevel3, async ctx => {
        const {id: project_id, anchor_id, schedule_id} = ctx.params;
        await app.model.DetailAnchorSchedule.destroy(
            {where: {id: schedule_id, anchor_id, project_id}});
        if (0 === app.model.DetailAnchorSchedule.count({project_id, anchor_id}))
          app.model.ProjectAnchor.destroy({where: {project_id, anchor_id}});
        ctx.body = 'ok';
      });

  /**获取日报 的    单日  数据*/
  router.get(prefix + '/:id/report/:date', middleware.api(4), checkLevel3,
      async ctx => {
        let {id: project_id, date} = ctx.params;
        ctx.body = await ctx.app.spiderReportData.get({project_id, date});
        ctx.body.project.role = await ctx.service.project.userRole(
            ctx.params.id, ctx.user.id);
      });

  /**获取日报  活跃主播    多日  数据*/
  router.get(prefix + '/:project_id/report/:start/:end', async ctx => {
    ctx.body = await app.spiderReportData.getActiveAnchor(ctx.params);
  });

  /**增加 删除 项目的 负责人、执行人员*/
  router.get(prefix + '/:id/:action/:type/:user_id', middleware.api(3),
      checkLevel3, async ctx => {
        const {User, UserLevel} = app.model;
        const {id, action, type, user_id} = ctx.params;
        if (type === 'manager' && ctx.role !== 0)
          return ctx.helper.error('你的权限不能管理项目负责人');
        const user = await User.findOne({
          raw: true,
          where: {id: user_id},
          include: [{model: UserLevel, as: 'level'}],
        });
        if (!user)
          return ctx.helper.error('不存在的用户');
        if (user['level.id'] <= 2)
          return ctx.helper.error('管理员账号不需要与项目有任何关系');

        if (type === 'manager') {
          if (action === 'add')
            ctx.service.project.addManager(ctx.project, user);
          else if (action === 'remove')
            ctx.service.project.removeManager(ctx.project, user);
        } else if (type === 'member') {
          if (action === 'add')
            ctx.service.project.addMember(ctx.project, user);
          else if (action === 'remove')
            ctx.service.project.removeMember(ctx.project, user);
        }
        ctx.body = user;
      });
};